// pages/payConfig/payConfig.js
import * as API_Order from '../../api/order'
import * as API_Product from '../../api/product'
import * as API_Coupon from '../../api/coupon'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    needPrice: 0,
    product: {},
    saleState: true,
    couponList: [],
    couponsIndex: 1,
    couponParams: {
      storeId: '',
      useState: 'N',
      canUseState: 'Y',
      overdueStateParam: 'N'
    },
    pageStatus: false,
    isVip: 'N',
    checked: false,
    integral: {},
    url: "",
    orderId: ''
  },
  checkboxChange() {
    this.setData({
      checked: !this.data.checked
    })
    if(this.data.checked) {
      this.setData({
        needPrice: (this.data.needPrice - this.data.integral.money) <= 0 ? 0.01 : (this.data.needPrice - this.data.integral.money).toFixed(2) * 1
      })
    } else {
      this.setData({
        needPrice: (this.data.needPrice + this.data.integral.money) <= 0 ? 0.01 : (this.data.needPrice + this.data.integral.money).toFixed(2) * 1
      })
    }
  },
  flushInfo() {
    const member = wx.getStorageSync('member')
    this.setData({
      userInfo: member
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      isVip: getApp().globalData.isVip
    })
    console.log(options.id)
    if(options.id) {
      this.setData({
        orderId: options.id
      })
    }
    let productIdBack = options.productId;

    getApp().https.ajax({
      method: 'post',
      url: '/product/getInfo',
      data: {
        id: options.productId,
        storeId: options.storeId
      },
      loading: true
    }).then(res => {
      if (!res.data.storeId) {
        res.data.storeId = parseInt(options.storeId)
      }
      if (!res.data.productId) {
        res.data.productId = parseInt(options.productId)
      }
      this.setData({
        product: res.data,
        needPrice: res.data.price,
        'couponParams.storeId': res.data.storeId
      })
      this.data.couponParams.storeId = res.data.storeId
      this.data.couponParams.productId = res.data.productId
      this.data.couponParams.bakId = productIdBack
      API_Coupon.getCanUseCoupons(this.data.couponParams).then(ref => {
        const rowData = [...ref.data.rows]
        
        if (rowData.length > 0) {
          rowData.unshift({
            id: -1,
            couponId: -1,
            couponName: '不使用',
            canUseState: "Y",
            money: 0,
            minPrice: 0
          })
          let money = rowData[1].money
          this.setData({
            needPrice: res.data.price - money <= 0 ? 0.01 : ((res.data.price * 100) - (money * 100)) / 100
          })
          for (let item of rowData) {
            item.showPicker = item.couponName + "  -" + item.money
          }
          this.setData({
            couponsIndex: 1,
            couponList: rowData
          })
        }
        this.getInterial(this.data.needPrice)
      })
      
    })
    // API_Product.getTemp(productIdBack).then(res => {
    //   if (!res.data.storeId) {
    //     res.data.storeId = parseInt(options.storeId)
    //   }
    //   this.setData({
    //     product: res.data,
    //     needPrice: res.data.price,
    //     'couponParams.storeId': res.data.storeId
    //   })
    //   this.data.couponParams.storeId = res.data.storeId
    //   this.data.couponParams.productId = res.data.productId
    //   this.data.couponParams.bakId = productIdBack
    //   API_Coupon.getCanUseCoupons(this.data.couponParams).then(ref => {

    //     if (ref.data.rows.length > 0) {
    //       let money = ref.data.rows[0].money
    //       this.setData({
    //         needPrice: res.data.price - money < 0 ? 0.01 : ((res.data.price * 100) - (money * 100)) / 100
    //       })
    //       for (let item of ref.data.rows) {
    //         item.showPicker = item.couponName + "  -" + item.money
    //       }
    //       this.setData({
    //         couponList: ref.data.rows
    //       })
    //     }
    //   })
    // })
    
  },
  changeCoupons(e) {
    console.log(this.data.checked)
    if (!this.data.couponList.length > 0) {
      return
    }
    let that = this
    let price = that.data.product.price
    let money = that.data.couponList[e.detail.value].money
    let coundPrice = price - money <= 0 ? 0.01 : ((price * 100) - (money * 100)) / 100

    that.getInterial(coundPrice).then(() => {
        if(that.data.checked) {
            coundPrice = (coundPrice - that.data.integral.money) <= 0 ? 0.01 : ((coundPrice * 100) - (that.data.integral.money * 100)) / 100
          }
          that.setData({
            couponsIndex: e.detail.value,
            needPrice: coundPrice
            // needPrice: price - money < 0 ? 0.01 : ((price * 100) - (money * 100)) / 100
          })
    })
    
  },
  sales(e) {
    console.log(this.data.checked)
    this.setData({
      saleState: false
    })
    let that = this;
    let params = {
      productId: that.data.product.productId,
      storeId: that.data.product.storeId
    }
    let coupon = that.data.couponList[that.data.couponsIndex]
    if (coupon && that.data.couponsIndex != 0) {
      params.couponId = coupon.couponId
    }
    if(that.data.checked) {
      params.integral = that.data.integral.integral
    }

    API_Order.createOrder(params).then(res => {
      this.setData({
        saleState: true
      })
      if (res.code == 200) {
        let orderId = res.data.id;
        that.setData({
          orderId
        })
        that.toPay(orderId);
      } else {
        wx.showToast({
          title: res.msg
        })
      }
    })
  },

  getInterial: function(price) {
    const that = this
    return API_Order.getInterial(price).then(res => {
      that.setData({
        integral: res.data
      })
    })
  },
  toPay: function (orderId) {
    let that = this
    let params = {
      orderId: orderId
    };
    API_Order.delayPay(params).then(res => {
      if (res.code == 200) {

        let payment = res.data;

        if (payment.status == "succeeded") {
          let expend = payment.expend;
          let pay_info = JSON.parse(expend.pay_info);

          wx.requestPayment({
            'timeStamp': pay_info.timeStamp,
            'nonceStr': pay_info.nonceStr,
            'package': pay_info.package,
            'signType': pay_info.signType,
            'paySign': pay_info.paySign,
            'success': function (res) {
              wx.showToast({
                title: '支付成功',
              })
              that.setData({
                url: '/pages/orderDetail/orderDetail?id='+that.data.orderId+'&origin=1'
              })
              setTimeout(() => {
                that.setData({
                  pageStatus: true
                })
              }, 1000)

            },
            'fail': function (res) {

            },
            'complete': function (res) {

            }
          })
        }


      } else {
        wx.showToast({
          title: res.msg
        })
      }

    })

  },
  pageLeave () {
    this.setData({
      pageStatus: false
    })
  },
  toHome () {
    wx.reLaunch({
      url: '/pages/home/home',
    })
  },
  toDetail () {
    // wx.navigateTo({
    //   url: '/pages/myOrderList/myOrderList?state=wait_use&tabIndex=2',
    // })
    // wx.navigateTo({
    //   url: '/pages/orderDetail/orderDetail?id='+this.data.orderId+'&origin=1',
    // })
    wx.reLaunch({
      url: '/pages/orderDetail/orderDetail?id='+this.data.orderId+'&origin=1',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})